<template>
  <div class="department-container">
    <div class="app-container">
      <!-- 上导航栏 -->
      <page-tools>
        <template #left>
          <span>在职人员数据{{ total }}条</span>
        </template>
        <template #right>
          <el-button type="warning" size="small" @click="$router.push('/import')">导入excel</el-button>
          <el-button type="danger" size="small" @click="exportExcel">导出excel</el-button>
          <el-button type="primary" size="small" @click="addRoleBtn">新增员工</el-button>
        </template>
      </page-tools>
      <!-- 表格内容 -->
      <el-card style="margin-top: 10px;">
        <el-table
          class="my-table"
          :data="tableData"
          border
          style="width: 100%"
        >
          <el-table-column label="序号" type="index" width="50px" />
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="工号" prop="workNumber" />
          <el-table-column label="聘用形式" prop="formOfEmployment">
            <template slot-scope="scope">
              <div @click="fn(scope)">{{ formatEmployment(scope.row.formOfEmployment) }}</div>
            </template>
          </el-table-column>
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column label="入职时间" prop="timeOfEntry" />
          <el-table-column label="操作" width="200px">
            <template slot-scope="scope">
              <el-button
                type="text"
                size="middle"
                @click="$router.push(`/employees/detail?id=${scope.row.id}`)"
              >查看</el-button>
              <el-button type="text" size="middle" @click="assignRoleBtn(scope.row.id)">分配角色</el-button>
              <el-button type="text" size="middle" @click="delEmployeesBtn(scope.row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-pagination
          :current-page.sync="pageInfo.page"
          :page-size="pageInfo.size"
          layout="total, prev, pager, next"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </el-card>
      <!-- 新增按钮弹窗 -->
      <el-dialog
        title="提示"
        :visible.sync="dialogVisible"
        width="55%"
        :before-close="handleClose"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        :show-close="false"
        @close="dialogClose"
      >
        <add-dialog ref="dialogRef" @success="addSuccess" @close="dialogVisible=false" />
      </el-dialog>

      <!-- 分配权限弹框 -->
      <el-dialog
        title="分配角色"
        :visible.sync="roleDialogVisble"
        width="50%"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        :show-close="false"
      >
        <AssignPermission v-if="roleDialogVisble" :current-id="currentId" @close="roleDialogVisble=false" />
      </el-dialog>

    </div>
  </div>
</template>
<script>
// test(id) {
//   const obj = {}
//       EmployeeEnum.hireType.forEach(item => {
//         obj[item.id] = item.value
//       })
//       return obj[id] ? obj[id] : '非正式'
// }
// console.log(test(123));
import { getRolesListRequest, delEmployeesRequest } from '@/api/employees'
import EmployeeEnum from '@/constant/employees'
import addDialog from './addDialog.vue'
import { transformEnToZhCN } from '@/utils'
import AssignPermission from './AssignRole'
export default {
  components: {
    addDialog,
    AssignPermission
  },
  data() {
    return {
      tableData: [],
      pageInfo: {
        page: 1,
        size: 5
      },
      total: 0,
      dialogVisible: false,
      roleDialogVisble: false,
      currentId: ''
    }
  },
  created() {
    this.getRolesList()
  },
  methods: {
    async getRolesList() {
      try {
        const res = await getRolesListRequest(this.pageInfo)
        // console.log(res)
        if (res.success) {
          this.tableData = res.data.rows
          this.total = res.data.total
          // console.log(this.total)
        } else {
          this.$message.error(res.message)
        }
      } catch (error) {
        this.$message.error('获取角色列表失败!')
      }
    },
    handleSizeChange() {},
    handleCurrentChange(value) {
      console.log(value)
      this.pageInfo.page = value
      this.getRolesList()
    },
    formatEmployment(id) {
      // 从hireType中 通过id找到对应的元素的value
      const obj = {}
      EmployeeEnum.hireType.forEach(item => {
        obj[item.id] = item.value
      })
      return obj[id] ? obj[id] : '非正式'
      // return  ? '正式' : '非正式'
    },
    handleClose() {},
    // 增加员工按钮
    addRoleBtn() {
      this.dialogVisible = true
    },
    addSuccess() {
      this.dialogVisible = false
      this.getRolesList()
    },
    // 点击查看数据回显
    getRoleByIdBtn(id) {
      this.getRoleById(id)
      this.dialogVisible = true
    },
    // async getRoleById(id) {
    //   try {
    //     const res = await getRoleByIdRequest(id)
    //     console.log('getRoleByIdRequest: ', res)
    //     if (res.success) {
    //       this.$message.success(res.message)
    //       this.dialogVisible = false
    //     } else {
    //       this.$message.success(res.message)
    //     }
    //   } catch (err) {
    //     console.log('getRoleByIdRequest: ', err)
    //   }
    // },
    delEmployeesBtn(id) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        console.log(123)
        this.delEmployeesInfo(id)
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    async delEmployeesInfo(id) {
      try {
        const res = await delEmployeesRequest(id)
        console.log('delEmployeesRequest: ', res)
        if (res.success) {
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          this.getRolesList()
        } else {
          this.$message.error(res.message)
        }
      } catch (err) {
        console.log('delEmployeesRequest: ', err)
      }
    },
    dialogClose() {
      this.$refs.dialogRef.reset()
    },
    // exportExcel() {
    //   import('@/vendor/Export2Excel').then(excel => {
    //     excel.export_json_to_excel({
    //       header: ['姓名', '年龄', '住址'],
    //       data: [
    //         ['彭翀', 9527, '前端85'],
    //         ['朱志文', 9527, '前端85'],
    //         ['杨优', 9527, '前端85'],
    //         ['韩钢', 9527, '前端85']
    //       ],
    //       filename: '二组帅哥美女名单',
    //       autoWidth: true,
    //       bookType: 'xlsx'
    //     })
    //     this.downloadLoading = false
    //   })
    // }
    exportExcel() {
      // 使用之前需要先下载两个包 file-saver script-loader
      // 要么使用 npm install file-saver script-loader
      // 要么使用 yarn add file-saver script-loader  两种方式二选一
      // console.log(this.tableData) // 服务器返回的 原始数据
      // const res = transformEnToZhCN(this.tableData) // 被我们转换过后的 excel需要的新数据
      // console.log(res)
      import('@/vendor/Export2Excel').then(excel => {
        const { header, data } = transformEnToZhCN(this.tableData)
        excel.export_json_to_excel({
          // 表头
          // header: ['姓名', '年龄', '住址'],
          header,
          // data是表格的数据，是一个二维数组
          data,
          filename: '导出文件的名称',
          autoWidth: true,
          bookType: 'xlsx'
        })
        this.downloadLoading = false
      })
    },
    assignRoleBtn(id) {
      this.roleDialogVisble = true
      this.currentId = id
    }
  }
}
</script>
<style lang="scss" scoped>
.my-table {
  margin-top: 20px;
  text-align: center;
}
</style>
